<script lang="ts">
export default {
  name: "HomeBar"
};
</script>

<script setup lang="ts">
import { ECharts } from "echarts";
import echarts from "/@/plugins/echarts";
import { onMounted, nextTick, ref, watch } from "vue";
import { tryOnUnmounted, useTimeoutFn } from "@vueuse/core";

import {
  addResizeListener,
  removeResizeListener
} from "element-plus/lib/utils/resize-event";
import { isArray } from "/@/utils/is";

const props = defineProps({
  echartData: {
    type: Object,
    default: () => {}
  }
});

let echartInstance: ECharts;

const ExpenditureBar = ref<HTMLElement | null>(null) as any;
const chart = ref<HTMLElement | null>(null) as any;

function initechartInstance(data1, data2, data3, data4) {
  let inputData = [];
  let dataLength;
  if (data3 && data3[0] && isArray(data3[0])) {
    dataLength = data1.length;
    data3.forEach((item, index) => {
      let obj = {
        name: index + 1 + "月已投入总额",
        type: "bar",
        stack: "total",
        tooltip: {
          valueFormatter: function (value) {
            return value;
          }
        },
        data: data3[index]
      };
      inputData.push(obj);
    });
  } else {
    inputData = data3;
  }

  const echartDom = chart.value;
  if (!echartDom) return;
  // @ts-ignore
  echartInstance = echarts.init(echartDom);
  echartInstance.clear(); //清除旧画布 重新渲染

  let option = {
    // color: ["#00e6ad", "#59a0ff", "#ffc500"],
    color: ["#85A5FF", "#59a0ff", "#ffc500"],
    grid: {
      left: 100,
      bottom: 120,
      right: 40
    },
    // tooltip: {
    //   trigger: "axis",
    //   axisPointer: {
    //     type: "shadow"
    //   }
    // },

    // legend: {
    //   // orient: "vertical",
    //   data: ["预算金额", "实际金额"]
    // },
    // tooltip: {
    //   trigger: "axis",
    //   axisPointer: {
    //     type: "cross",
    //     crossStyle: {
    //       color: "#999"
    //     }
    //   }
    // },
    // toolbox: {
    //   feature: {
    //     dataView: { show: true, readOnly: false },
    //     magicType: { show: true, type: ["line", "bar"] },
    //     restore: { show: true },
    //     saveAsImage: { show: true }
    //   }
    // },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross", // 默认为直线，可选为：'line' | 'shadow'
        crossStyle: {
          color: "#999"
        }
      },
      formatter: param => {
        var str = "";
        var str1 = "";
        var str2 = "";
        let inputVal = 0;
        for (const item of param) {
          if (item.seriesIndex === 0) {
            item.seriesName &&
              (str +=
                item.marker +
                " " +
                item.seriesName +
                "：" +
                item.value.toFixed(2) +
                "<br>");
          } else {
            inputVal += item.value;
            item.seriesName &&
              (str2 +=
                item.marker +
                " " +
                item.seriesName +
                "：" +
                item.value.toFixed(2) +
                "<br>");
          }
        }
        str1 =
          '<span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:#1197b8"></span>' +
          " " +
          "已投入总额" +
          "：" +
          inputVal.toFixed(2) +
          "<br>";
        return str + str1 + str2;
      }
    },
    legend: {
      top: 20,
      // data: ["预算总额", "已投入总额", "预算执行率"]
      data: ["预算总额"]
    },
    xAxis: [
      {
        splitLine: {
          show: false
        },
        type: "category",
        data: data1,
        axisPointer: {
          type: "shadow"
        },
        axisLabel: {
          formatter: function (value) {
            var ret = "";
            var maxLength = 1;
            var valLength = value.length;
            var rowN = Math.ceil(valLength / maxLength);
            if (rowN > 1) {
              for (var i = 0; i < rowN; i++) {
                var temp = "";
                var start = i * maxLength;
                var end = start + maxLength;
                temp = value.substring(start, end) + "\n";
                ret += temp;
              }
              return ret;
            } else {
              return value;
            }
          }
        }
      }
    ],
    yAxis: [
      {
        type: "value",
        name: "百万元",
        axisLine: {
          show: true
        },
        splitLine: {
          show: false
        },
        axisLabel: {
          // formatter: "{value} (元)"
          formatter: function (value, index) {
            value = (value / 1000000).toFixed(2);
            return value;
          }
        }
      }
      // {
      //   type: "value",
      //   name: "",
      //   axisLine: {
      //     show: true
      //   },
      //   splitLine: {
      //     show: false
      //   },
      //   axisLabel: {
      //     formatter: "{value}%"
      //   }
      // }
    ],
    series: [
      {
        name: "预算总额",
        type: "bar",
        tooltip: {
          valueFormatter: function (value) {
            return value;
          }
        },
        data: data2
      },
      ...inputData,
      // {
      //   name: "已投入总额",
      //   type: "bar",
      //   stack: "total",
      //   tooltip: {
      //     valueFormatter: function (value) {
      //       return value;
      //     }
      //   },
      //   data: data3
      // },
      {
        name: "",
        type: "bar",
        data: dataLength ? new Array(dataLength).fill(0) : data3,
        stack: "total",
        label: {
          show: true,
          position: "top",
          color: "#333"
        }
      }
      // {
      //   name: "预算执行率",
      //   type: "line",
      //   yAxisIndex: 1,
      //   tooltip: {
      //     valueFormatter: function (value) {
      //       return value + "%";
      //     }
      //   },
      //   data: data4
      // }
    ]
  };

  function getSum(params) {
    var datavalue = 0;
    for (var i = 0; i < series.length; i++) {
      datavalue += series[i].data[params.dataIndex];
    }
    return (datavalue / 1000000).toFixed(2);
  }

  var series = option.series.splice(1, option.series.length - 1);
  series[series.length - 1].label.formatter = getSum;
  option.series.splice(1, 0, ...series);
  echartInstance.setOption(option);
}

onMounted(() => {
  nextTick(() => {
    addResizeListener(ExpenditureBar.value, resetRender);
    // useEventListener("resize", () => {
    //   resetRender();
    // });
  });
});

watch(
  () => props.echartData,
  newVal => {
    if (newVal) {
      const { barData, monthData } = newVal;
      nextTick(() => {
        initechartInstance(barData[0], barData[1], monthData, barData[2]);
      });
    }
  }
);

const resetRender = () => {
  if (!echartInstance) return;
  useTimeoutFn(() => {
    echartInstance.resize();
  }, 180);
};

tryOnUnmounted(() => {
  if (!echartInstance) return;
  echartInstance.dispose();
  echartInstance = null;
  removeResizeListener(ExpenditureBar.value, resetRender);
});
</script>

<template>
  <div ref="ExpenditureBar">
    <div class="ExpenditureBar" ref="chart"></div>
  </div>
</template>

<style lang="scss" scoped>
.title {
  font-size: 16px;
  color: $defaultColor;
  margin: 10px 0;
  height: 24px;
}
.ExpenditureBar {
  width: 100%;
  height: 300px;
}
</style>
